package com.naodong.shenluntiku.mvp.presenter;

import android.text.TextUtils;

import com.naodong.shenluntiku.mvp.contract.FindContract;
import com.naodong.shenluntiku.mvp.model.bean.BoxNetworkData;
import com.naodong.shenluntiku.mvp.model.bean.GradeChartData;
import com.naodong.shenluntiku.mvp.model.bean.SubjectType;
import com.naodong.shenluntiku.mvp.model.data.manager.BoxManager;
import com.naodong.shenluntiku.mvp.model.error.ApiError;
import com.naodong.shenluntiku.mvp.model.error.DefaultResponseErrorListener;
import com.naodong.shenluntiku.mvp.model.error.ResponseErrorListener;
import com.naodong.shenluntiku.mvp.model.error.ResultHandleSubscriber;
import com.naodong.shenluntiku.util.GsonConvert;
import com.naodong.shenluntiku.util.RxUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.annotations.NonNull;
import me.shingohu.man.di.scope.ActivityScope;
import me.shingohu.man.mvp.BasePresenter;


/**
 * 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
 * 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
 * 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
 * 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
 * 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
 * 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
 */


/**
 * Created by hujie on 17/5/8.
 */

@ActivityScope
public class FindPresenter extends BasePresenter<FindContract.Model, FindContract.View> {

    Map<Integer, GradeChartData> gradeChartMap;
    ArrayList<SubjectType> subjectTypes;

    @Inject
    public FindPresenter(FindContract.Model model, FindContract.View rootView) {
        super(model, rootView);
    }

    public void getFindSubjectItems(boolean isRefresh) {
        if (!isRefresh) {//是否刷新操作
            //获取本地数据
            String cache = BoxManager.getInstance().queryBoxNetworkDataByIdAndType(BoxNetworkData.FIND_GRADE_TESTS_ID);
            if (!TextUtils.isEmpty(cache)) {//有缓存在，按下拉刷新样式请求
                getView().onRefreshBegin();
                isRefresh = true;
                List<SubjectType> data = GsonConvert.fromJsonList(cache, SubjectType.class);
                FindPresenter.this.subjectTypes = new ArrayList<>(data);
                getView().showFindSubjectItem(data);
            }
        }
        getFindSubjectList(isRefresh);
    }

    /**
     * 获取题型列表
     */
    public void getFindSubjectList(boolean refresh) {
        addDisposable(RxUtils.applySchedulers(mModel.getFindSubjectItems(), disposable -> {
            if (!refresh) {
                getView().onRequesrStart();
            }
        }, () -> {
            if (refresh) {
                getView().onRefreshFinish();
            } else {
                getView().onRequestFinish();
            }
        }, getView())
                .subscribeWith(new ResultHandleSubscriber<List<SubjectType>>(ResponseErrorListener.EMPTY) {
                    @Override
                    public void onNext(@NonNull List<SubjectType> findSubjectItems) {
                        if (refresh) {
                            clearGradeChartData();
                        }
                        BoxManager.getInstance().putBoxNetworkData(BoxNetworkData.FIND_GRADE_TESTS_ID, GsonConvert.toJson(findSubjectItems));
                        FindPresenter.this.subjectTypes = new ArrayList<>(findSubjectItems);
                        getView().showFindSubjectItem(findSubjectItems);
                    }
                }));
    }


    /**
     * 获取成绩图表数据
     *
     * @param id
     */
    public void getGradeChartData(int id) {
        if (gradeChartMap == null) {
            gradeChartMap = new HashMap();
        }

        if (gradeChartMap.containsKey(id)) {
            getView().showGradeChartData(gradeChartMap.get(id));
            return;
        }
        addDisposable(RxUtils.applySchedulers(mModel.getFindSubjectItemGradeChartData(id), getView()).subscribeWith(new ResultHandleSubscriber<GradeChartData>(new DefaultResponseErrorListener() {
            @Override
            public void handleErrorCode204(ApiError apiError) {
                getView().showGradeNoData();

            }
        }) {
            @Override
            public void onNext(@NonNull GradeChartData gradeChartData) {
                gradeChartMap.put(id, gradeChartData);
                getView().showGradeChartData(gradeChartData);
            }
        }));
    }

    public ArrayList<SubjectType> getSubjectTypes() {
        return subjectTypes;
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        getFindSubjectItems(true);
    }

    /**
     * 清除旧的数据
     */
    public void clearGradeChartData() {
        if (gradeChartMap != null) {
            gradeChartMap.clear();
        }
    }


}